package com.zwps.biz.domain.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zwps.biz.api.model.dto.dsmdrfsrhrds.DsmDfrSrhrdsDTO;
import com.zwps.biz.api.model.dto.dsmspgpzwl.DsmHistoryDateDTO;
import com.zwps.biz.api.model.vo.dsmdfrsrhrds.*;

import com.zwps.biz.api.model.vo.dsmspgpzwl.DsmHistoryDateVo;
import com.zwps.biz.api.model.vo.dsmspgpzwl.DsmSpgPzwDateVO;
import com.zwps.biz.api.model.vo.pubsectionall.PubSectionAllVOS;
import com.zwps.biz.dal.db.dao.DsmDfrSrhrdsDAO;
import com.zwps.biz.dal.db.dao.DsmSpgPzwlDAO;
import com.zwps.biz.dal.db.dao.PubPointAllDAO;
import com.zwps.biz.dal.db.dao.PubSectionAllDAO;
import com.zwps.biz.dal.db.object.DsmDfrSrhrdsDO;

import com.zwps.biz.dal.db.object.DsmSpgPzwlDO;
import com.zwps.biz.domain.service.DsmDfrSrhrdsService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;


/**
 *
 */
@Service
public class DsmDfrSrhrdsServiceImpl extends ServiceImpl<DsmDfrSrhrdsDAO, DsmDfrSrhrdsDO> implements DsmDfrSrhrdsService {

    @Autowired
    private DsmDfrSrhrdsDAO dsmDfrSrhrdsDAO;
    @Autowired
    private PubPointAllDAO pointAllDAO;
    @Autowired
    private DsmSpgPzwlDAO spgPzwlDAO;

    @Autowired
    private PubSectionAllDAO pubSectionAllDAO;


    @Override
    public List<DsmAVO> getHorizontal(DsmDfrSrhrdsDTO srhrdsDTO) {
        return queryDsmData(srhrdsDTO, Collections.emptyList());
    }


    @Override
    public List<DsmAVO> getSideSeam(DsmDfrSrhrdsDTO srhrdsDTO) {
        String[] contents = new String[]{"测缝计", "机器视觉"};
        srhrdsDTO.setSccd(StrUtil.isNotEmpty(srhrdsDTO.getSccd()) ? "45" : null);
        return queryDsmData(srhrdsDTO, Arrays.asList(contents));
    }

    @Override
    public List<DsmDfrSrhrdsMinMaxVO> getMinMax(DsmDfrSrhrdsDTO srhrdsDTO) {
        List<String> stringList = dsmDfrSrhrdsDAO.getMpcd(srhrdsDTO.getSccd());
        List<String> indicatorList = Arrays.asList(
                "XHRDS",
                "YHRDS",
                "ZHRDS",
                "original_XHRDS",
                "original_YHRDS",
                "original_ZHRDS"
        );

        Map<String, Object> params = new HashMap<>();
        params.put("stringList", stringList);
        params.put("indicatorList", indicatorList);
        return dsmDfrSrhrdsDAO.getMinMax(params, srhrdsDTO);
    }

    @Override
    public List<String> getStation() {
        return dsmDfrSrhrdsDAO.getStation();
    }

    @Override
    public List<DsmDfrSrhrdsVO> getLastStation() {
        return dsmDfrSrhrdsDAO.getLastStation();

    }

    @Override
    public List<PubSectionAllVOS> getData() {
        List<PubSectionAllVOS> list = pubSectionAllDAO.getLists();
        list.forEach(item -> {
            if (item.getChildren() == null) {
                item.setChildren(new ArrayList<>());
            }
            item.getChildren().addAll(pubSectionAllDAO.getSccds(item.getHycncd()));
        });
        return list;
    }

    @Override
    public IPage<DsmAVO> getDsmDfrSrhrdsByMpcd(DsmHistoryDateDTO historyDateDTO) {
        System.out.println("aaaa"+historyDateDTO);
        String table = "";
        if ( null == historyDateDTO.getChoose() ||historyDateDTO.getChoose() == 0){
            table="";
        }
        if (null != historyDateDTO.getChoose() && historyDateDTO.getChoose()==1){
            table="_manual";
        }
        IPage<DsmAVO> page = new Page<>(historyDateDTO.getPageNum(), historyDateDTO.getPageSize());
        return   dsmDfrSrhrdsDAO.gethistoryData(page,historyDateDTO.getMpcd(),historyDateDTO.getStartTime(),historyDateDTO.getEndTime(),historyDateDTO.getType(),table);
    }

    public List<DsmAVO> queryDsmData (DsmDfrSrhrdsDTO srhrdsDTO, List<String> contents) {
        List<DsmAVO> avos = new ArrayList<>();
//        if (null!=srhrdsDTO.getChoose() && srhrdsDTO.getChoose().equals("1")) {
//            srhrdsDTO.setPageSize(1);
//        } else {
//            srhrdsDTO.setPageSize(10);
//        }
        if (null == srhrdsDTO.getPages() || 0 == srhrdsDTO.getPages()) {
            srhrdsDTO.setPages(1);
        }
        if (null == srhrdsDTO.getPageSize() || 0 == srhrdsDTO.getPageSize()) {
            srhrdsDTO.setPageSize(10);
        }
        List<String> stringList = pointAllDAO.getVertical(srhrdsDTO.getSccd(), srhrdsDTO.getHycncd(), contents);
        if (null == stringList || stringList.size() == 0) {
            return avos;
        }
        Page<DsmDfrSrhrdsDO> page = new Page<>(srhrdsDTO.getPages(), srhrdsDTO.getPageSize());

        IPage<Map<String, Object>> data = dsmDfrSrhrdsDAO.getHorizontal(
                page,
                stringList,
                srhrdsDTO.getStartTime(),
                srhrdsDTO.getEndTime()
        );
        avos = processQueryResults(data.getRecords());
        return avos;

    }

    public List<DsmAVO> processQueryResults(List<Map<String, Object>> queryResults) {
        List<DsmAVO> results = new ArrayList<>();

        for (Map<String, Object> row : queryResults) {

            // 初始化动态列存储的 Map
            Map<String, Object> dynamicColumns = new HashMap<>();

            for (Map.Entry<String, Object> entry : row.entrySet()) {
                DsmAVO queryResult = new DsmAVO();
                String columnName = entry.getKey();
                Object columnValue = entry.getValue();
                if (!columnName.equals("times")) {
                    queryResult.setName(columnName);
                    Date sqlDate = (Date) row.get("times");

                    LocalDateTime localDateTime = sqlDate.toLocalDate()  // 先转 LocalDate
                            .atStartOfDay(); // 再
                    queryResult.setTime((localDateTime));
                    // 排除 "times" 字段
                    if (!Arrays.asList("times").contains(columnName)) {
                        if (columnValue instanceof String) {
                            String columnValueStr = (String) columnValue;
                            if (columnValueStr.contains(",")) {
                                String[] splitValues = columnValueStr.split(",");
                                queryResult.setX((splitValues.length > 0) ? truncateToTwoDecimals(splitValues[0]) : null);
                                queryResult.setY((splitValues.length > 0) ? truncateToTwoDecimals(splitValues[1]) : null);
                                queryResult.setZ((splitValues.length > 0) ? truncateToTwoDecimals(splitValues[2]) : null);
                                queryResult.setLat((splitValues.length > 0) ? splitValues[3] : null);
                                queryResult.setLnt((splitValues.length > 0) ? splitValues[4] : null);

                            } else {
                                dynamicColumns.put(columnName, columnValue);
                            }
                        } else {
                            // 非字符串类型直接存储
                            dynamicColumns.put(columnName, columnValue);
                        }
                    }
                    results.add(queryResult);
                }
            }

        }

        return results;
    }

    private String truncateToTwoDecimals(String value) {
        if (value == null) return null;
        int dotIndex = value.indexOf(".");
        if (dotIndex == -1 || dotIndex + 3 > value.length()) {
            return value;
        }
        return value.substring(0, dotIndex + 3);
    }
}




